Skip to main content

Python Dictionary

banner-python

πŸ“š fun_with_python_dictionaries.md​

🐍 Fun with Python Dictionaries! 🧠πŸ’₯​

Welcome to the world of Python Dictionaries – where curly braces {} become treasure chests, and key-value pairs are your loot! βš”οΈπŸ’°

A Dictionary in Python is like your magical backpack: unordered (so it might take a sec to find stuff), mutable (you can change what’s inside), and indexed (but in a key-unique way).

In short:

🧳 Dictionary = HashTable from Java + Python’s charm + chaos of an unordered sock drawer.


1. 🧾 Creating the Dictionary​

1.1. With Curly Braces – The OG Way​

Just slap some key-value pairs inside {} like it’s a grocery list.

# an empty dictionary
Dict = {}

# a dictionary with 3 items
Dict = {
"Name": "sujit",
"Age": 30,
"Blog": "fossguru"
}

print(Dict)

πŸ–¨οΈ Output:

{'Age': 30, 'Name': 'sujit', 'Blog': 'fossguru'}

1.2. Using the dict() Constructor – The Fancy Pants Way​

Why just write curly braces when you can summon dictionaries using dict()? 🎩✨

# Creating a Dictionary with dict() method
Dict = dict({1: 'Python', 2: 'Example'})
print(Dict)

# Creating a Dictionary with tuples
Dict = dict([(1, 'Python'), (2, 'Example')])
print(Dict)

# Notice that the keys are not the string literals
Dict = dict(firstName="sujit", lastName="karne", age=30)
print(Dict)

πŸ–¨οΈ Output:

{1: 'Python', 2: 'Example'}
{1: 'Python', 2: 'Example'}
{'firstName': 'sujit', 'lastName': 'karne', 'age': 30}

2. πŸ” Accessing the Values – Show Me the Loot​

Two ways to get to your precious dictionary values:

  • Dict[key] – Classic but may scream (KeyError) if key is missing!
  • Dict.get(key) – Nicer, calmer, lets you provide a backup value.
Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}

print(Dict["name"])
print(Dict.get("age"))

print(Dict.get("country"))
print(Dict.get("country", "India"))

πŸ–¨οΈ Output:

sujit
30
None
India

3. πŸ•΅οΈβ€β™€οΈ Is That Key Even There?​

Before opening a mystery box, make sure it exists. 🧐

3.1. key in Dict​

Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}

if "name" in Dict:
print("name is present")
else:
print("name is not present")

πŸ–¨οΈ Output:

name is present

3.2. key not in Dict​

Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}

if "country" not in Dict:
print("country is not present")
else:
print("country is present")

πŸ–¨οΈ Output:

country is not present

4. πŸ› οΈ Adding / Updating the Values​

New name? Different country? Dictionaries don’t mind your identity crisis.

Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}
print(Dict["name"])

# Updating the name
Dict["name"] = "Alex"
print(Dict["name"])

# Updating the name with update() method
Dict.update({"name": "Brian"})
print(Dict["name"])

# Adding a new item - country
Dict.update({"country": "India"})
print(Dict["country"])

πŸ–¨οΈ Output:

sujit
Alex
Brian
India

5. πŸ’£ Deleting Dictionary Items​

5.1. Using del – The Nuclear Option​

Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}
print(Dict)

# Deleting the name
del Dict["name"]
print(Dict)

# Deleting the dictionary
del Dict
print(Dict)

πŸ–¨οΈ Output:

{'name': 'sujit', 'blog': 'fossguru', 'age': 30}
{'blog': 'fossguru', 'age': 30}

Traceback (most recent call last):
File "<string>", line 14, in <module>
NameError: name 'Dict' is not defined

5.2. pop() – A Gentle Kick Out​

Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}
print(Dict)

# Deleting the name
Dict.pop("name")
print(Dict)

πŸ–¨οΈ Output:

{'name': 'sujit', 'blog': 'fossguru', 'age': 30}
{'blog': 'fossguru', 'age': 30}

5.3. clear() – The Clean Slate​

Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}
print(Dict)

# Clear all the dictionary items
Dict.clear()
print(Dict)

πŸ–¨οΈ Output:

{'name': 'sujit', 'blog': 'fossguru', 'age': 30}
{}

6. πŸ” Iterating Over Dictionary Items – For Loop Party πŸŽ‰β€‹

6.1. Classic for Loop​

Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}

for k in Dict:
v = Dict[k]
print("Key :" + k + ", Value: " + str(v))

πŸ–¨οΈ Output:

Key :name, Value: sujit
Key :blog, Value: fossguru
Key :age, Value: 30

6.2. Values Only – values() method​

Dict = {
"name":"sujit",
"blog":"fossguru"
}

for v in Dict.values():
print("Value :" + v)

πŸ–¨οΈ Output:

Value :sujit
Value :fossguru

6.3. Full Combo – items() method​

Dict = {
"name":"sujit",
"blog":"fossguru"
}

for i in Dict.items():
print(i)
print("Key :" + i[0] + ", Value: " + i[1])

πŸ–¨οΈ Output:

('name', 'sujit')
Key :name, Value: sujit

('blog', 'fossguru')
Key :blog, Value: fossguru

7. πŸ§™β€β™‚οΈ Built-in Dictionary Magic Spells (a.k.a. Methods)​

MethodDescription
clear()Clears everything. Poof!
copy()Makes a clone, no evil twin.
fromkeys()Mass-produce keys with the same value.
get()Retrieves values gently.
items()Shows key-value pairs in a tuple outfit.
keys()Just the keys, please.
pop()Bye-bye specific key.
popitem()Bye-bye last item.
setdefault()Adds key if missing.
update()Updates or adds stuff.
values()Just the values, no strings attached.

Examples? Coming right up 🍿:

Dict = {"name":"sujit", "blog":"fossguru"}
Dict.clear()
print(Dict)
{}
Dict = {"name":"sujit", "blog":"fossguru"}
myDict = Dict.copy()
print(myDict)
{'name': 'sujit', 'blog': 'fossguru'}
keys = ('key1', 'key2', 'key3')
value = 0

Dict = dict.fromkeys(keys, value)

print(Dict)
{'key1': 0, 'key2': 0, 'key3': 0}
Dict = {"name":"sujit", "blog":"fossguru"}

print(Dict.get("name"))
sujit

...and so on! You’ve got the power now 🧠⚑


πŸŽ‰ Congrats! You're now officially a Python Dictionary Wizard! πŸ§™β€β™€οΈπŸ